package com.yy.lib_audio.mediaplayer.core;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;

import com.yy.lib_audio.app.AudioSlot;
import com.yy.lib_audio.mediaplayer.events.AudioCompleteEvent;
import com.yy.lib_audio.mediaplayer.events.AudioErrorEvent;
import com.yy.lib_audio.mediaplayer.events.AudioLoadEvent;
import com.yy.lib_audio.mediaplayer.events.AudioReleaseEvent;
import com.yy.lib_audio.mediaplayer.events.AudioStartEvent;
import com.yy.lib_audio.mediaplayer.model.AudioBean;

import org.greenrobot.eventbus.EventBus;

import androidx.annotation.NonNull;

public class AudioPlayer implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnErrorListener, AudioFocusManager.AudioFocusListener {
    private static final String TAG = "AudioPlayer";
    private static final int TIME_MSG = 0x01;
    private static final int TIME_INVALID = 100;

    private CustomMediaPlayer mCustomMediaPlayer;
    private WifiManager.WifiLock mWifiLock;
    private AudioFocusManager mAudioFocusManager;
    private boolean isPauseByFocusLoss;

    private Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TIME_MSG:
                    break;
            }
        }
    };

    public AudioPlayer() {
        init();
    }

    private void init() {
        mCustomMediaPlayer = new CustomMediaPlayer();
        mCustomMediaPlayer.setWakeMode(AudioSlot.getContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mCustomMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mCustomMediaPlayer.setCompleteListener(this);
        mCustomMediaPlayer.setOnPreparedListener(this);
        mCustomMediaPlayer.setOnBufferingUpdateListener(this);
        mCustomMediaPlayer.setOnErrorListener(this);
        mWifiLock = ((WifiManager) AudioSlot.getContext().getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL, TAG);
        mAudioFocusManager = new AudioFocusManager(AudioSlot.getContext(), this);
    }

    private void setVolume(float leftVol, float rightVol) {
        mCustomMediaPlayer.setVolume(leftVol, rightVol);
    }

    private void start() {
        if (mAudioFocusManager.requestAudioFocus()) {
            Log.e(TAG, "获取音频焦点失败");
        }
        mCustomMediaPlayer.start();
        mWifiLock.acquire();
        EventBus.getDefault().post(new AudioStartEvent());
    }

    public void load(AudioBean audioBean) {
        try {
            mCustomMediaPlayer.reset();
            mCustomMediaPlayer.setDataSource(audioBean.mUrl);
            mCustomMediaPlayer.prepareAsync();
            EventBus.getDefault().post(new AudioLoadEvent(audioBean));
        } catch (Exception e) {
            EventBus.getDefault().post(new AudioErrorEvent());
        }
    }

    public void pause() {
        if (getStatus() == CustomMediaPlayer.Status.STARTED) {
            mCustomMediaPlayer.pause();
            if (mWifiLock.isHeld()) {
                mWifiLock.release();
            }
            if (mAudioFocusManager != null) {
                mAudioFocusManager.abandonAudioFocus();
            }
            EventBus.getDefault().post(new AudioStartEvent());
        }
    }

    public void resume() {
        if (getStatus() == CustomMediaPlayer.Status.PAUSED) {
            start();
        }
    }

    public void release() {
        if (mCustomMediaPlayer != null) {
            mCustomMediaPlayer.release();
            mCustomMediaPlayer = null;
        }
        if (mAudioFocusManager != null) {
            mAudioFocusManager.abandonAudioFocus();
            mAudioFocusManager = null;
        }
        if (mWifiLock.isHeld()) {
            mWifiLock.release();
            mWifiLock = null;
        }
        EventBus.getDefault().post(new AudioReleaseEvent());
    }

    public CustomMediaPlayer.Status getStatus() {
        if (mCustomMediaPlayer != null) {
            return mCustomMediaPlayer.getState();
        }
        return CustomMediaPlayer.Status.STARTED;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        Log.d(TAG, "percent:" + percent);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        EventBus.getDefault().post(new AudioCompleteEvent());
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        EventBus.getDefault().post(new AudioErrorEvent());
        return true;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        start();
    }

    @Override
    public void audioFocusGrant() {
        //再次获取音频焦点
        setVolume(1.0f, 1.0f);
        if (isPauseByFocusLoss) {
            resume();
        }
        isPauseByFocusLoss = false;
    }

    @Override
    public void audioFocusLoss() {
        //永久失去焦点
        pause();
    }

    @Override
    public void audioFocusLossTransient() {
        pause();
        isPauseByFocusLoss = true;
    }

    @Override
    public void audioFocusLossDuck() {
        //瞬间失去焦点
        setVolume(0.5f, 0.5f);
    }
}
